package com.opener.common.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author baboy
 * @date 09/12/2016
 */
public class CookieUtils {
    public static Cookie getCookie(HttpServletRequest request, String name, String domain, String path){
        Cookie[] cookies = request.getCookies();
        if(cookies == null) {
            return null;
        }
        for (int i = 0; i< cookies.length; i++){
            Cookie cookie = cookies[i];
            if (cookie.getName().equalsIgnoreCase(name)){
                if(domain != null && !domain.equalsIgnoreCase(cookie.getDomain())){
                    continue;
                }
                if (path != null && !path.equalsIgnoreCase(cookie.getPath())){
                    continue;
                }
                return cookie;
            }
        }
        return null;
    }
    public static Cookie getCookie(HttpServletRequest request, String name){
        return getCookie(request, name, null, null);
    }
    public static List<Cookie> getCookies(HttpServletRequest request, String name){
        List<Cookie> ret = new ArrayList<>();
        Cookie[] cookies = request.getCookies();
        if(cookies == null)
            return null;
        for (int i = 0; i< cookies.length; i++){
            Cookie cookie = cookies[i];
            if (cookie.getName().equalsIgnoreCase(name)){
                ret.add( cookie );
            }
        }
        return ret.size()>0 ? ret : null;
    }
    public static void removeCookie(HttpServletResponse response, String name, String domain, String path){
        Cookie cookie = new Cookie(name,"");
        if (cookie != null){
            cookie.setMaxAge(0);
            cookie.setPath("/");
            if(domain != null){
                cookie.setDomain(domain);
            }
            if(path != null){
                cookie.setPath(path);
            }
            response.addCookie(cookie);
        }
    }
    public static void removeCookie(HttpServletResponse response, Cookie cookie){
        removeCookie(response, cookie.getName(), cookie.getDomain(), cookie.getPath());
    }
    public static Cookie createCookie(String name, String v, String domain, String path, int maxAge){
        Cookie cookie = new Cookie(name,v==null?"":v);
        if (domain != null) {
            cookie.setDomain(domain);
        }
        cookie.setPath(path==null?"/":path);
        cookie.setMaxAge(maxAge);
        return cookie;
    }
    public static void addCookie(HttpServletResponse response, String name, String v, String domain, String path, int maxAge){
        Cookie cookie = createCookie(name,v,domain,path,maxAge);
        response.addCookie(cookie);
    }
}
